package vertx;

import io.vertx.core.Vertx;
import io.vertx.core.http.HttpMethod;
import io.vertx.core.http.HttpServer;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.core.http.HttpServerResponse;
import io.vertx.ext.web.Router;

/**
 * Created by szc on 6/22/2016.
 */
public class Runner {
    public static void main(String[] args) {
        Vertx vertx = Vertx.vertx();

        HttpServer httpServer = vertx.createHttpServer();

        Router router = Router.router(vertx);

        router.route("/catalogue/products/:producttype/:productid/").handler(routingContext -> {
            HttpServerRequest request = routingContext.request();
            String productType = request.getParam("producttype");
            String productid = request.getParam("productid");
            routingContext.response().setChunked(true).write("productType:" + productType + ", productid:" + productid).end();
        });


        router.route("/some/path/").handler(routingContext -> {
            System.out.println("blocing thread:" + Thread.currentThread().getName());
            HttpServerResponse response = routingContext.response();
            response.setChunked(true);
            response.write("route1\n");
            routingContext.vertx().setTimer(2000, tick -> routingContext.next());
        });
        router.route("/some/path/").handler(routingContext -> {
            System.out.println("blocing thread:" + Thread.currentThread().getName());
            HttpServerResponse response = routingContext.response();
            response.setChunked(true);
            response.write("route2\n");
            routingContext.vertx().setTimer(2000, tick -> routingContext.next());
            System.out.println("out");
        });

        router.route("/some/path/").blockingHandler(routingContext -> {
            //this handler will be executing in serial. the next request will wait for this one.
            // if set the orded = false, this handler will executing in parallel.
            try {
                System.out.println("blocing thread:" + Thread.currentThread().getName());
                Thread.sleep(2000);
                routingContext.response().write("route blocking\n");
                routingContext.next();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("out");
        });

        router.route("/some/path/").handler(routingContext -> {
            System.out.println("blocing thread:" + Thread.currentThread().getName());
            HttpServerResponse response = routingContext.response();
            response.setChunked(true);
            response.write("route3\n");
            response.end();
        });


        httpServer.requestHandler(router::accept);

        httpServer.listen(8080);


    }
}
